package com.baoyouqun.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.base.utils.ConvertUtils;
import com.baoyouqun.domain.CreateCmd.UserVipTimeCreateCmd;
import com.baoyouqun.domain.Query.UserVipTimeQuery;
import com.baoyouqun.domain.UpdateCmd.UserVipTimeUpdateCmd;
import com.baoyouqun.domain.VO.NonLeopardVisitDTO;
import com.baoyouqun.domain.VO.UserVipTimeVO;
import com.baoyouqun.domain.VO.VipLevelVO;
import com.baoyouqun.entity.UserVipTime;
import com.baoyouqun.mapper.UserVipTimeMapper;
import com.baoyouqun.service.SystemConfigService;
import com.baoyouqun.service.UserVipTimeService;
import com.baoyouqun.service.VipLevelService;
import jakarta.annotation.Resource;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class UserVipTimeServiceImpl extends ServiceImpl<UserVipTimeMapper, UserVipTime> implements UserVipTimeService {

    @Resource
    private UserVipTimeMapper userVipTimeMapper;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private VipLevelService vipLevelService;

    @Override
    public Map<String, Boolean> getValidVipMap(List<String> userIds, LocalDateTime now) {
        if (CollUtil.isEmpty(userIds)) {
            return Collections.emptyMap();
        }

        // 查询用户有效的VIP记录（未过期且已开始）
        List<UserVipTime> validVips = baseMapper.selectList(new QueryWrapper<UserVipTime>()
                .in("user_id", userIds)
                .le("start_time", now)  // 会员已开始
                .ge("end_time", now)    // 会员未过期
                .last("limit 1"));      // 每个用户取一条有效记录

        // 构建用户ID到有效状态的映射
        Map<String, Boolean> resultMap = userIds.stream()
                .collect(Collectors.toMap(
                        Function.identity(),
                        userId -> validVips.stream().anyMatch(vip -> userId.equals(vip.getUserId()))
                ));

        return resultMap;
    }

    @Override
    public void createBaoZhiHao(String userId) {
        UserVipTimeVO userVipTimeVO = getCurrentVip(userId);
        if (Objects.nonNull(userVipTimeVO)) {
            return;
        }
        Long days = 10L;
        NonLeopardVisitDTO nonLeopardVisit = systemConfigService.getNonLeopardVisit();
        UserVipTime entity = new UserVipTime();
        if (nonLeopardVisit != null) {
            days = nonLeopardVisit.getDurationDay();
        }
        entity.setEndTime(LocalDateTime.now().plusYears(days));
        entity.setUserId(userId);
        entity.setStartTime(LocalDateTime.now());
        entity.setVipLevelId("001");
        save(entity);
    }

    @Override
    public Set<String> selectValidVipUserIds(List<String> candidateIds) {
        if (CollUtil.isEmpty(candidateIds)) {
            return Collections.emptySet();
        }
        LocalDateTime now = LocalDateTime.now();

        // 1. 查询所有未过期的VIP记录
        LambdaQueryWrapper<UserVipTime> vipWrapper = new LambdaQueryWrapper<UserVipTime>()
                .select(UserVipTime::getUserId)
                .in(CollUtil.isNotEmpty(candidateIds), UserVipTime::getUserId, candidateIds)
                .le(UserVipTime::getStartTime, now)
                .gt(UserVipTime::getEndTime, now);

        Set<String> validVipUserIdSet = userVipTimeMapper.selectObjs(vipWrapper).stream()
                .map(obj -> (String) obj)
                .collect(Collectors.toSet());
        return validVipUserIdSet;
    }

    @Override
    public boolean checkByUserId(String userId) {
        UserVipTimeVO userVipTimeVO = getCurrentVip(userId);
        return Objects.nonNull(userVipTimeVO);
    }

    @Override
    public SingleResponse<UserVipTime> createTemp(String userId) {
        UserVipTimeVO userVipTimeVO = getCurrentVip(userId);
        if (Objects.nonNull(userVipTimeVO)) {
            return SingleResponse.buildSuccess();
        }

        Long days = 3L;
        NonLeopardVisitDTO nonLeopardVisit = systemConfigService.getNonLeopardVisit();
        UserVipTime entity = new UserVipTime();
        if (nonLeopardVisit != null) {
            days = nonLeopardVisit.getDurationDay();
        }
        entity.setEndTime(LocalDateTime.now().plusDays(days));
        entity.setUserId(userId);
        entity.setStartTime(LocalDateTime.now());
        entity.setVipLevelId("002");
        Boolean result = save(entity);
        if (!result) {
            return SingleResponse.buildFailure("100101", "创建失败");
        }
        return SingleResponse.of(entity);
    }

    @Override
    public SingleResponse<UserVipTimeVO> create(UserVipTimeCreateCmd cmd) {
        UserVipTime entity = new UserVipTime();
        BeanUtils.copyProperties(cmd, entity);
        Boolean result = save(entity);
        if (!result) {
            return SingleResponse.buildFailure("100101", "创建失败");
        }

        UserVipTimeVO vo = new UserVipTimeVO();
        BeanUtils.copyProperties(entity, vo);
        return SingleResponse.of(vo);
    }

    @Override
    public Response update(UserVipTimeUpdateCmd cmd) {
        if (Objects.isNull(cmd)) {
            return Response.buildFailure("100301", "参数不能为空");
        }
        if (StringUtil.isBlank(cmd.getId())) {
            return Response.buildFailure("100302", "ID不能为空");
        }
        UserVipTime oldEntity = getById(cmd.getId());
        if (Objects.isNull(oldEntity)) {
            return Response.buildFailure("100303", "未查询到此数据");
        }
        BeanUtils.copyProperties(cmd, oldEntity);
        Boolean result = updateById(oldEntity);
        if (result) {
            return Response.buildSuccess();
        } else {
            return Response.buildFailure("100304", "更新失败");
        }
    }

    @Override
    public UserVipTimeVO selectById(String id) {
        UserVipTime entity = userVipTimeMapper.selectById(id);
        UserVipTimeVO vo = new UserVipTimeVO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    @Override
    public IPage<UserVipTimeVO> pageVo(UserVipTimeQuery query) {
        IPage<UserVipTime> page = new Page<UserVipTime>(query.getCurrent(), query.getSize());
        page = page(page, new LambdaQueryWrapper<UserVipTime>());
        Page<UserVipTimeVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<UserVipTimeVO> records = ConvertUtils.copyBeanList(page.getRecords(), UserVipTimeVO.class);
        voPage.setRecords(records);
        return voPage;
    }

    @Override
    public UserVipTimeVO selectByUserId(String userId) {
        if (StringUtil.isBlank(userId)) {
            return null;
        }

        UserVipTime entity = null;
        // 第一步：优先查询 viptypeId 为 001 的记录（核心新增逻辑）
        entity = getOne(
                new LambdaQueryWrapper<UserVipTime>()
                        .eq(UserVipTime::getUserId, userId) // userId 已判空，无需重复判断
                        .eq(UserVipTime::getVipLevelId, "001"), // 优先筛选 viptypeId=001
                false // 查不到时返回 null，不抛异常（安全查询）
        );

        // 第二步：若未查到 viptypeId=001 的记录，查询该用户下的任意一条 VIP 记录（原逻辑）
        if (entity == null) {
            entity = getOne(
                    new LambdaQueryWrapper<UserVipTime>()
                            .eq(UserVipTime::getUserId, userId),
                    false // 同样避免多记录抛异常
            );
        }

        // 转换为 VO 并返回（原逻辑不变）
        return getUserVipTimeVO(entity);
    }

    private UserVipTimeVO getUserVipTimeVO(UserVipTime entity) {
        if (entity == null) {
            return null;
        }

        String vipLevelName = "";
        if (StringUtil.isNotBlank(entity.getVipLevelId())) {
            VipLevelVO vipLevel = vipLevelService.selectById(entity.getVipLevelId());
            if (vipLevel != null) {
                vipLevelName = vipLevel.getLevelName();
            }
        }
        UserVipTimeVO vo = ConvertUtils.copyBean(entity, UserVipTimeVO.class);
        vo.setVipLevelName(vipLevelName);
        return vo;
    }

    @Override
    public Map<String, Boolean> getVipStatusByUserIds(List<String> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return new HashMap<>();
        }

        // 查询所有用户的VIP信息
        List<UserVipTime> vipTimes = list(
                new LambdaQueryWrapper<UserVipTime>()
                        .in(UserVipTime::getUserId, userIds)
        );

        // 构建用户ID到VIP状态的映射
        Map<String, Boolean> result = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();

        for (String userId : userIds) {
            // 默认不是VIP
            result.put(userId, false);
        }

        for (UserVipTime vipTime : vipTimes) {
            // 检查VIP是否在有效期内
            boolean isValid = vipTime.getEndTime() != null &&
                    vipTime.getEndTime().isAfter(now);
            result.put(vipTime.getUserId(), isValid);
        }

        return result;
    }

    /**
     * 查询用户当前有效的会员记录
     */
    @Override
    public UserVipTimeVO getCurrentVip(String userId) {
        if (StringUtil.isBlank(userId)) {
            return null;
        }
        LocalDateTime now = LocalDateTime.now();
        // 查询未过期的会员记录（开始时间≤现在，结束时间>现在）
        LambdaQueryWrapper<UserVipTime> wrapper = new LambdaQueryWrapper<UserVipTime>()
                .eq(UserVipTime::getUserId, userId)
                .le(UserVipTime::getStartTime, now)
                .gt(UserVipTime::getEndTime, now)
                .orderByDesc(UserVipTime::getEndTime) // 优先取过期时间最晚的
                .last("LIMIT 1");

        UserVipTime vipTime = userVipTimeMapper.selectOne(wrapper);
        UserVipTimeVO vo = ConvertUtils.copyBean(vipTime, UserVipTimeVO.class);
        if (vo != null) {
            vo.setVipLevelName("VIP会员"); // 固定会员名称（可根据vipLevelId关联字典表）
        }
        return vo;
    }

    /**
     * 筛选有效会员用户ID列表
     */
    @Override
    public List<String> getEffectiveVipUserIdList(List<String> userIdList, String memberLevel) {
        LocalDateTime now = LocalDateTime.now();

        // 1. 查询所有未过期的VIP记录
        LambdaQueryWrapper<UserVipTime> vipWrapper = new LambdaQueryWrapper<UserVipTime>()
                .select(UserVipTime::getUserId)
                .in(CollUtil.isNotEmpty(userIdList), UserVipTime::getUserId, userIdList)
                .le(UserVipTime::getStartTime, now)
                .gt(UserVipTime::getEndTime, now);

        Set<String> validVipUserIdSet = userVipTimeMapper.selectObjs(vipWrapper).stream()
                .map(obj -> (String) obj)
                .collect(Collectors.toSet());

        // 2. 根据会员等级筛选
        switch (memberLevel) {
            case "1": // VIP会员：仅保留未过期VIP用户
                return new ArrayList<>(validVipUserIdSet);
            case "0": // 临时会员：仅保留非VIP用户
                return userIdList.stream()
                        .filter(userId -> !validVipUserIdSet.contains(userId))
                        .collect(Collectors.toList());
            default: // 未指定等级：返回所有初始用户ID
                return userIdList;
        }
    }

}